package com.heima.wemedia.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    //注入file方法(需引依赖)
    @Autowired
    FileStorageService fileStorageService;

    /**
     * 上传图片方法
     * @param multipartFile
     * @return
     */


    @Value("${file.oss.profix}")
    String profix;
    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 上传素材(至oss)
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1. 检查文件是否存在
        if(multipartFile == null || multipartFile.getSize() == 0){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"文件不存在");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN,"需要登录");
        }
        //2.上传文件到oss
        try {
            String oriName = multipartFile.getOriginalFilename();
            String suffix = oriName.substring(oriName.lastIndexOf("."));// .jpg
            //uuid设置文件名
            String fileName = UUID.randomUUID().toString().replaceAll("-", "");
            //工具类上传到oss
            String fileUrl = fileStorageService.store(profix, fileName + suffix, multipartFile.getInputStream());
            //3. 创建素材表信息，将图片路径存入
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(user.getId());
            // 设置oss中的文件路径
            wmMaterial.setUrl(fileUrl);
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());
            //4. 将素材保存到数据库
            this.save(wmMaterial);
            wmMaterial.setUrl(webSite + fileUrl);
            //5. 封装返回结果
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件上传出现异常=>>{}",e.getMessage());
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文件上传失败");
        }
    }

    /**
     * 查找素材回显
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1.检查参数
        dto.checkParam();

        //2.封装查询条件
        IPage<WmMaterial> pageReq=new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.<WmMaterial>lambdaQuery();
        if(dto.getIsCollection()!=null && dto.getIsCollection().intValue() == 1){
            queryWrapper.eq(WmMaterial::getIsCollection,1);
        }
        //从本地线程获取登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        queryWrapper.eq(WmMaterial::getUserId,user.getId());
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        //3.执行查询
        IPage<WmMaterial> pageResult = this.page(pageReq, queryWrapper);
        //给url路径加访问前缀路径
        List<WmMaterial> records = pageResult.getRecords();
        if(records != null && records.size()>0){
            for (WmMaterial record : records) {
                record.setUrl(webSite + record.getUrl());
            }
        }

        //4.封装结果并返回
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        pageResponseResult.setData(records);
        return pageResponseResult;
    }
}